<template>
  <div>
    <treeselect
      v-model="deptId"
      :options="deptOptions"
      :disabled="disabled"
      noResultsText="暂无数据"
      :clearable='clearable'
      :normalizer="normalizer"
      placeholder="选择所属部门"
      class="treeselect-main"
      style="width: 100%; height: 32px"
    />
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { listDept } from "@/api/system/dept"
export default {
  components: { Treeselect },
  props: {
    isAddress: {
      type: Boolean,
      default: false,
    },
    value: { type: [Number, String], default: null },
    pdeptId: [Number, String],
    disabled: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  model: {
    // 需要双向绑定的 props 变量名称，也就是父组件通过 v-model 与子组件双向绑定的变量
    prop: "value",
  },
  watch: {
    // 监听 sonValue 临时变量，如果临时变量发生变化，那么通过 $emit 将新的值传递给父组件
    value:{
      handler(value){
        this.deptId = value
      },
      immediate:true

      // 【注意】newValue x需要和 model.event 定义的值一致
      // this.$emit('emitDeptId', this.deptId)
    },
    deptId(value) {
      // if (this.isAddress) {
      //   checkProcess({ param: this.deptId, type: 2 })
      //     .then((res) => {
      //     })
      //     .catch((res) => {
      //       this.$refs.ruleForm.validateField("workUnitAddress")
      //     })
      // }
      // 【注意】newValue x需要和 model.event 定义的值一致
      this.$emit("emitDeptId", this.deptId)
    },
  },
  data() {
    return {
      deptOptions: [],
      deptId: this.value,
    }
  },
  created() {
    this.init()
  },
  mounted() {},

  methods: {
    init() {
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId")
      })
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      }
    },
  },
}
</script>

<style scoped>
/* Treeselect */
.treeselect-main {
  width: 200px;
  line-height: 32px;
  height: 32px;
}
.treeselect-main .vue-treeselect__placeholder {
  line-height: 32px;
}

.treeselect-main /deep/ .vue-treeselect__control {
  height: 32px;
}
</style>
